package what.basic.textcomponent;
import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

import java.awt.*;
import java.awt.event.*;
public class Jtextfieldplaindocument extends JPanel{
	private static final long serialVersionUID=1L;
	JFrame lf=null;
	public void add(Component c,GridBagConstraints cs,int x, int y,int w,int h){
		cs.gridx=x;
		cs.gridy=y;
		cs.gridwidth=w;
		cs.gridheight=h;
		add(c,cs);
	}
	Jtextfieldplaindocument(){
		lf=new JFrame("a login frame test");
		lf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		GridBagLayout lay=new GridBagLayout();
		setLayout(lay);
		lf.add(this,BorderLayout.WEST);
		lf.setSize(300, 150);
		Toolkit kit=Toolkit.getDefaultToolkit();
		Dimension sz=kit.getScreenSize();
		int width=sz.width;
		int height=sz.height;
		int x=(width-lf.WIDTH)/2;
		int y=(height-lf.HEIGHT)/2;
		lf.setLocation(x, y);
		JButton ok=new JButton("login");
		JButton cancel=new JButton("cancel");
		JLabel name=new JLabel("username");
		JLabel title=new JLabel("login frame");
		JLabel password=new JLabel("password");
		JTextField nameinput=new JTextField(new Jtextfield_fixedlengthdocument(10),"",10);
		final JTextField passinput=new JTextField(15);
		GridBagConstraints cs=new GridBagConstraints();
		cs.fill=GridBagConstraints.NONE;
		cs.anchor=GridBagConstraints.EAST;
		cs.weightx=3;
		cs.weighty=4;
		cs.insets=new Insets(2,2,2,2);
		add(title,cs,0,0,2,1);
		add(name,cs,0,1,2,1);
		add(password,cs,0,2,1,1);
		add(nameinput,cs,2,1,1,1);
		add(passinput,cs,2,2,1,1);
		add(ok,cs,0,3,1,1);
		add(cancel,cs,2,3,1,1);
		lf.setResizable(false);
		lf.setVisible(true);
	}

//public class test{
	public static void main(String[] args){
		Jtextfieldplaindocument log=new Jtextfieldplaindocument();
	//}
	}
	class Jtextfield_fixedlengthdocument extends PlainDocument{
		private int maxLength;
		public Jtextfield_fixedlengthdocument(int maxLength){
		this.maxLength=maxLength;}
	
	public void insertString(int offset,String str,AttributeSet att)throws BadLocationException{
		if(getLength()+str.length()>maxLength){
			Toolkit.getDefaultToolkit().beep();
		}
		else{
			super.insertString(offset,str,att);
		}
	}}
}